package com.castle.fortress.admin.orders.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.castle.fortress.admin.member.entity.MemberEntity;
import com.castle.fortress.admin.orders.entity.SaleCouponEntity;
import com.castle.fortress.admin.orders.enums.CouponGetTypeEnum;
import com.castle.fortress.admin.orders.enums.CouponPayTypeEnum;
import com.castle.fortress.admin.orders.enums.CouponStatusEnum;
import com.castle.fortress.admin.utils.BizCommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.orders.entity.SaleCouponDataEntity;
import com.castle.fortress.admin.orders.dto.SaleCouponDataDto;
import com.castle.fortress.admin.orders.mapper.SaleCouponDataMapper;
import com.castle.fortress.admin.orders.service.SaleCouponDataService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 优惠券领取记录 服务实现类
 *
 * @author whc
 * @since 2023-01-06
 */
@Service
public class SaleCouponDataServiceImpl extends ServiceImpl<SaleCouponDataMapper, SaleCouponDataEntity> implements SaleCouponDataService {
    /**
     * 获取查询条件
     *
     * @param saleCouponDataDto
     * @return
     */
    public QueryWrapper<SaleCouponDataEntity> getWrapper(SaleCouponDataDto saleCouponDataDto) {
        QueryWrapper<SaleCouponDataEntity> wrapper = new QueryWrapper();
        if (saleCouponDataDto != null) {
            SaleCouponDataEntity saleCouponDataEntity = ConvertUtil.transformObj(saleCouponDataDto, SaleCouponDataEntity.class);
            wrapper.eq(saleCouponDataEntity.getMemberId() != null, "member_id", saleCouponDataEntity.getMemberId());
            wrapper.eq(saleCouponDataEntity.getCouponId() != null, "coupon_id", saleCouponDataEntity.getCouponId());
            wrapper.eq(saleCouponDataEntity.getGetType() != null, "get_type", saleCouponDataEntity.getGetType());
            wrapper.eq(StrUtil.isNotEmpty(saleCouponDataEntity.getOrderSn()), "order_sn", saleCouponDataEntity.getOrderSn());
            wrapper.eq(saleCouponDataEntity.getStatus() != null, "status", saleCouponDataEntity.getStatus());
            wrapper.eq(saleCouponDataEntity.getPayType() != null, "pay_type", saleCouponDataEntity.getPayType());
            wrapper.orderByDesc("create_time");
        }
        return wrapper;
    }


    @Override
    public IPage<SaleCouponDataDto> pageSaleCouponData(Page<SaleCouponDataDto> page, SaleCouponDataDto saleCouponDataDto) {
        QueryWrapper<SaleCouponDataEntity> wrapper = getWrapper(saleCouponDataDto);
        Page<SaleCouponDataEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<SaleCouponDataEntity> saleCouponDataPage = baseMapper.selectPage(pageEntity, wrapper);
        Page<SaleCouponDataDto> pageDto = new Page(saleCouponDataPage.getCurrent(), saleCouponDataPage.getSize(), saleCouponDataPage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(saleCouponDataPage.getRecords(), SaleCouponDataDto.class));
        return pageDto;
    }

    @Override
    public IPage<SaleCouponDataDto> pageSaleCouponDataExtends(Page<SaleCouponDataDto> page, SaleCouponDataDto saleCouponDataDto) {
        Map<String, Long> pageMap = BizCommonUtil.getPageParam(page);
        SaleCouponDataEntity saleCouponDataEntity = ConvertUtil.transformObj(saleCouponDataDto, SaleCouponDataEntity.class);
        List<SaleCouponDataEntity> saleCouponDataList = baseMapper.extendsList(pageMap, saleCouponDataEntity);
        Long total = baseMapper.extendsCount(saleCouponDataEntity);
        Page<SaleCouponDataDto> pageDto = new Page(page.getCurrent(), page.getSize(), total);
        pageDto.setRecords(ConvertUtil.transformObjList(saleCouponDataList, SaleCouponDataDto.class));
        return pageDto;
    }

    @Override
    public SaleCouponDataDto getByIdExtends(Long id) {
        SaleCouponDataEntity saleCouponDataEntity = baseMapper.getByIdExtends(id);
        return ConvertUtil.transformObj(saleCouponDataEntity, SaleCouponDataDto.class);
    }

    @Override
    public List<SaleCouponDataDto> listSaleCouponData(SaleCouponDataDto saleCouponDataDto) {
        QueryWrapper<SaleCouponDataEntity> wrapper = getWrapper(saleCouponDataDto);
        List<SaleCouponDataEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list, SaleCouponDataDto.class);
    }

    public void send(SaleCouponEntity coupon, Integer getNumber, List<MemberEntity> receivers) {
        //查询出应该排除的用户
//        baseMapper.cou
        final DateTime effectiveTime = new DateTime();
        final DateTime overdueTime = new DateTime();
        final HashMap<Long, HashMap<String, Long>> countMap = baseMapper.countGroupMemberId(coupon.getId());
        final ArrayList<SaleCouponDataEntity> list = new ArrayList<>();
        receivers.forEach(memberEntity -> {
            final HashMap<String, Long> stringIntegerHashMap = countMap.get(memberEntity.getId());
            //最多拥有-已有=剩余可得
            //如果剩余可得 2  本次发放1 那就发放1
            //如果剩余可得 1 本次发放2 那就方法1
            int decNumber = stringIntegerHashMap != null && stringIntegerHashMap.get("count") != null ? stringIntegerHashMap.get("count").intValue() : 0;
            final int remainNumber = coupon.getGetMax() - decNumber;
            final int giveNumber = remainNumber >= getNumber ? getNumber : remainNumber;
            System.out.println(giveNumber);
            for (Integer i = 0; i < giveNumber; i++) {
                SaleCouponDataEntity temp = new SaleCouponDataEntity();
                temp.setCouponId(coupon.getId());
                temp.setMemberId(memberEntity.getId());
                temp.setGetTime(new Date());
                temp.setGetType(CouponGetTypeEnum.ADMIN_GIVE.getCode());
                temp.setEffectiveTime(effectiveTime.toJdkDate());
                temp.setOverdueTime(overdueTime.toJdkDate());
                temp.setPayType(CouponPayTypeEnum.FREE.getCode());
                temp.setPayNumber(0);
                temp.setPointNumber(0);
                temp.setStatus(CouponStatusEnum.UNUSED.getCode());
                list.add(temp);
            }
        });
        saveBatch(list);
    }

    @Override
    public HashMap<Long, HashMap<String, Long>> countGroupByMemberId(Long memberId) {
        return baseMapper.countGroupByMemberId(memberId);
    }

}

